//
//  NewComprehensiveViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/11/19.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit

class NewComprehensiveViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {
    
    var companys: [JSON] = []
    
    var busines: [JSON] = []
    
    var others: [JSON] = []
    
    var selectedCompany: String = ""
    
    override var names: Array<String>{
        get{
            return ["GETORG","ZHPlan"]
        }
    }
    
    override func path(for name: String) -> String {
        if name == "GETORG" {
            return GETORG
        } else if name == "ZHPlan" {
            return NewZHPlan
        }
        return ""
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        if name == "GETORG" {
            return [:]
        } else if name == "ZHPlan" {
            var dic: [String: String] = [:]
            let startTime = (dateField.text ?? "")
            if startTime.count > 0 {
                dic["startTime"] = startTime + "-01-01"
            }
            if selectedCompany.count > 0 {
                dic["orgCode"] = selectedCompany
            }
            let endDate = (endDateField.text ?? "")
            if endDate.count > 0 {
                dic["endDate"] = endDate
            }
            return dic
        }else{
            return [:]
        }
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        get{
            return .lightContent
        }
    }
    
    @IBAction func clearAction(_ sender: Any) {
        var owncompany = JSON()
        for item in companys {
            if item.contents?["code"]?.rawString() == User.orgCode {
                owncompany = item
                break
            }
        }
        selectedCompany = owncompany.contents?["code"]?.rawString() ?? ""
        dateField.text = "2018"
        companyField.text = owncompany.contents?["name"]?.rawString()
        endDateField.text = ""
        self.load(with: "ZHPlan")
    }
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    @IBAction func beginDateShadowAction(_ sender: Any) {
        self.beginDateShadowField.becomeFirstResponder()
    }
    @IBAction func endDateShadowAction(_ sender: Any) {
        self.endDateShadowField.becomeFirstResponder()
    }
    
    @IBOutlet weak var companyField: UITextField!
//    @IBOutlet weak var beginDateShadowField: UITextField!
//    @IBOutlet weak var endDateShadowField: UITextField!
    let beginDateShadowField = UITextField()
    let endDateShadowField = UITextField()
    func popalert() -> Void {
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        for item in companys {
            
            let sheet = UIAlertAction.init(title: item.contents?["name"]?.rawString(), style: .default) { (action) in
                
                self.companyField.text = item.contents?["name"]?.rawString()
                
                self.selectedCompany = item.contents?["code"]?.rawString() ?? ""
                
                self.load(with: "ZHPlan")
            }
            alert.addAction(sheet)
        }
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        
        alert.addAction(cancel)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    override var shouldAutorotate: Bool {
        get {
            return true
        }
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        get {
            return UIInterfaceOrientationMask.portrait
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationItem.hidesBackButton = true
        if self.navigationController != nil {
            if let index = self.navigationController?.children.firstIndex(of: self) {
                if index > 0 {
                    let back = UIBarButtonItem.init(image: UIImage.init(named: "icon_nav_back")!.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(popobjc))
                    back.tintColor = .white
                    self.navigationItem.leftBarButtonItem = back
                } else {
                    self.navigationItem.leftBarButtonItem = nil
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.hidesBackButton = true
        if self.navigationController != nil {
            if let index = self.navigationController?.children.firstIndex(of: self) {
                if index > 0 {
                    let back = UIBarButtonItem.init(image: UIImage.init(named: "icon_nav_whiteback")!.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(popobjc))
                    back.tintColor = .white
                    self.navigationItem.leftBarButtonItem = back
                } else {
                    self.navigationItem.leftBarButtonItem = nil
                }
            }
        }
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
        self.navigationController?.navigationBar.barTintColor = UIColor.white
        self.navigationController?.navigationBar.setBackgroundImage(UIColor.hex("2B89DF").image(size: CGSize(width: UIScreen.main.bounds.size.width, height: 64)), for: .default)
    }
    
    override func success(for name: String) -> NetSuccess {
        func getOrgSuc(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.array {
                    self.companys = data
                    self.companyField.text = self.companys[0].contents?["name"]?.rawString()
                    self.selectedCompany = self.companys[0].contents?["code"]?.rawString() ?? ""
                    self.load(with: "ZHPlan")
                }
            }
        }
        
        func detail(json: JSON)->Void{
            if let success = json.contents?["success"]?.bool {
                if success == true  {
                    if let data = json.contents?["data"]?.dictionary {
                        self.busines = []
                        if let cgywsr = data["cgywsr"] {
                            self.busines.append(cgywsr)
                        }
                        if let cgywcb = data["cgywcb"] {
                            self.busines.append(cgywcb)
                        }
                        self.others = data["others"]?.array ?? []
                        self.tableView.reloadData()
                    }
                } else {
                    self.alert(json.contents?["errorMsg"]?.rawString())
                }
            } else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        if name == "GETORG" {
            return getOrgSuc
        } else {
            return detail
        }
    }
    
    var cellheiunit: CGFloat {
        get{
            return 1.6 + 11
        }
    }
    
    var cellheight: CGFloat {
        get{
            return (self.tableView.height - 10) / 12.6
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return busines.count
        } else {
            return others.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProgressTableViewCell")!
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return self.cellheight
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 10
        } else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return cellheight * 0.8
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if let cel = cell as? ProgressTableViewCell {
            switch indexPath.section{
            case 0:
                cel.model = busines[indexPath.row]
                break
            default:
                cel.model = others[indexPath.row]
                break
            }
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let contentheight = cellheight
        let view = UIView()
        let stackView = UIStackView.init(frame: CGRect.init(origin: CGPoint(x: 20, y: 0), size: CGSize(width: UIScreen.main.bounds.size.width - 40 , height: contentheight * 0.8)))
        stackView.axis = .horizontal
        stackView.alignment = .fill
        stackView.distribution = .fillEqually
        view.backgroundColor = UIColor.hex("FFF8E6")
        view.addSubview(stackView)
        let titles = ["综合计划","计划值","执行值","完成率"]
        for title in titles {
            let label = UILabel.init()
            label.width = title.size(with: UIFont.systemFont(ofSize: 14)).width
            label.height = title.size(with: UIFont.systemFont(ofSize: 14)).height
            label.text = title
            label.textAlignment = .center
            stackView.addArrangedSubview(label)
        }
        return view
    }
    
    @IBOutlet weak var dateField: UITextField!
    
    @IBOutlet weak var tableView: UITableView!
    @IBAction func showOrganizationsAction(_ sender: Any) {
        popalert()
    }
    
    @IBOutlet weak var nameLabel: UILabel!

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.section{
        case 0:
            if busines.count > indexPath.row {
                let type = String(busines[indexPath.row].contents?["typePlan"]?.int ?? 0)
                let incomecost = ICostDTViewController()
                incomecost.plantype = type
                let date = Date().year
                let title = String(date) + "年项目收入成本计划立项与执行情况表"
                incomecost.title = title
                incomecost.orgCode = self.selectedCompany
                self.push(destination: incomecost)
            }
            break
        default:
            break
        }
    }
    
    let datePicker = YearPicker.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: UIScreen.main.bounds.size.width, height: 220)))
    
    @objc override func endedit() {
        if beginDateShadowField.isFirstResponder {
            dateField.text = String(datePicker.selectedYear)
            beginDateShadowField.endEditing(true)
        } else if endDateShadowField.isFirstResponder {
            endDateField.text = String(endDatePicker.date.dateLineStr)
            endDateShadowField.endEditing(true)
        }
        self.view.endEditing(true)
    }
    
    @IBOutlet weak var endDateField: UITextField!
    let endDatePicker = UIDatePicker.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: UIScreen.main.bounds.size.width, height: 220)))
    
    @IBAction func searchAction(_ sender: Any) {
        self.load(with: "ZHPlan")
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField.isEqual(dateField) {
            textField.text = String(datePicker.selectedYear)
        } else {
            textField.text = String(endDatePicker.date.dateLineStr)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.separatorInset = .zero
        self.tableView.separatorStyle = .none
        dateField.delegate = self
        datePicker.years = (2018 ..< 2100).map({ (year) -> Int in
            return year
        })
        let year = Date().year - 2018
        datePicker.datePicker.selectRow(year, inComponent: 0, animated: false)
        dateField.text = String(datePicker.selectedYear)
        datePicker.backgroundColor = UIColor.white
        self.view.addSubview(beginDateShadowField)
        beginDateShadowField.inputView = datePicker
        beginDateShadowField.inputAccessoryView = self.toolbarview
        
        dateField.layer.masksToBounds = true
        dateField.layer.cornerRadius = 3
        endDatePicker.backgroundColor = UIColor.white
        endDatePicker.datePickerMode = .date
        endDatePicker.locale = Locale.init(identifier: "zh_CN")
        endDatePicker.minimumDate = Date.date(with: Date().year, month: 1, day: 1)
        self.view.addSubview(endDateShadowField)
        endDateShadowField.inputView = endDatePicker
        endDateShadowField.inputAccessoryView = self.toolbarview
        endDateField.layer.masksToBounds = true
        endDateField.layer.cornerRadius = 3
        self.tableView.tableFooterView = UIView()
        self.tableView.register(UINib.init(nibName: "ProgressTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "ProgressTableViewCell")
        self.load(with: "GETORG")
        // Do any additional setup after loading the view.
    }

}
